package org.blogwu.learn.multithread.chapter3.demo15;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

/**
 * fork/join  MapReduce学习
 *
 * @author hyf
 * @date 2018-10-05
 **/
public class Main {

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //19039462959 19989995149
        CountTask countTask = new CountTask(0, 200000L);
        ForkJoinTask<Long> result = forkJoinPool.submit(countTask);

        try {
            long res = result.get();
            System.out.println("res:" + res);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }


    static long count(long start, long end) {
        long sum = 0L;
        // 如果小于1w 没必要分批次
        if ((end - start) < 10000) {
            CountTask countTask = new CountTask(start, end);
        }
        ArrayList<CountTask> subTasks = new ArrayList<>();

        long numCount = end - start;
        long pos = start;
        if ((numCount % 100) == 0) {
            long step = numCount / 100;
            for (int i = 0; i < 100; i++) {
                long lastOne = pos + step;
                if (lastOne > end) lastOne = end;
                CountTask subTask = new CountTask(pos, lastOne);
                pos += step;
                subTasks.add(subTask);
                subTask.fork();
            }
        }
        for (CountTask t : subTasks) {
            sum += t.join();
        }
        return sum;
    }
}
